package cn.simon.free.ratelimiter.core.providers;

import cn.simon.free.ratelimiter.core.Rate;
import cn.simon.free.ratelimiter.utils.AllMethodRateLimiterUtils;
import com.google.common.util.concurrent.RateLimiter;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 本地缓存
 *
 * @author simon
 * @date 2020/3/25 10:44
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
public class LocalCache implements CacheProviders {

    @Override
    public Object getValue(String key) {
        return LocalCacheUtils.get(key);
    }

    @Override
    public void putKey(String key, Object rate) {
        LocalCacheUtils.put(key, rate);
    }

    @Override
    public boolean checkAuthority(String key) {
        RateLimiter methodRate = (RateLimiter) LocalCacheUtils.get(key);
        if (Objects.isNull(methodRate)) {
            Rate rate = AllMethodRateLimiterUtils.get(key);
            RateLimiter rateLimiter = RateLimiter.create(rate.getRate());
            putKey(key, rateLimiter);
            return true;
        } else {
            return methodRate.tryAcquire();
        }
    }
}

/**
 * 本地缓存工具类
 */
class LocalCacheUtils {

    private static final ConcurrentHashMap<String, Object> rateLimiterMaps = new ConcurrentHashMap<>();

    private LocalCacheUtils() {
    }

    /**
     * 取限流器
     *
     * @param key
     * @return
     */
    public static Object get(String key) {
        if (rateLimiterMaps.containsKey(key))
            return rateLimiterMaps.get(key);
        return null;
    }

    /**
     * 生成限流器
     *
     * @param key
     * @param rate
     */
    public static void put(String key, Object rate) {
        rateLimiterMaps.put(key, rate);
    }

}
